package device

import (
	"context"
	"time"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/device"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/predicate"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetDeviceListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetDeviceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDeviceListLogic {
	return &GetDeviceListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetDeviceListLogic) GetDeviceList(in *pancakebot.DeviceListReq) (*pancakebot.DeviceListResp, error) {
	var predicates []predicate.Device
	if in.CreatedAt != nil {
		predicates = append(predicates, device.CreatedAtGTE(time.UnixMilli(*in.CreatedAt)))
	}
	if in.UpdatedAt != nil {
		predicates = append(predicates, device.UpdatedAtGTE(time.UnixMilli(*in.UpdatedAt)))
	}
	result, err := l.svcCtx.DB.Device.Query().Where(predicates...).Page(l.ctx, in.Page, in.PageSize)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	resp := &pancakebot.DeviceListResp{}
	resp.Total = result.PageDetails.Total

	for _, v := range result.List {
		var outletPorts []*pancakebot.OutletPort
		for _, port := range v.OutletPorts {
			outletPorts = append(outletPorts, &pancakebot.OutletPort{
				Number: pointy.GetPointer(int64(port.Number)),
				Status: pointy.GetPointer(int64(port.Status)),
				InUse:  &port.InUse,
			})
		}

		deviceInfo := &pancakebot.DeviceInfo{
			Id:           &v.ID,
			CreatedAt:    pointy.GetPointer(v.CreatedAt.UnixMilli()),
			UpdatedAt:    pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			DeviceName:   &v.DeviceName,
			DeviceNo:     pointy.GetPointer(int64(v.DeviceNo)),
			DeviceStatus: pointy.GetPointer(int64(v.DeviceStatus)),
			Address:      &v.Address,
			Ext:          &v.Ext,
			Type:         pointy.GetPointer(int64(v.Type)),
			OutletPort:   outletPorts,
		}

		resp.Data = append(resp.Data, deviceInfo)
	}

	return resp, nil
}
